package com.liufei.class06;

import com.liufei.class04.ListNode;

import java.util.Comparator;
import java.util.PriorityQueue;

// https://leetcode.cn/problems/merge-k-sorted-lists/description/
public class Code01_MergeKSortedLists {

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        // 按照每个链表的头节点排序
        PriorityQueue<ListNode> heap = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val - o2.val;
            }
        });

        for (ListNode list : lists) {
            if (list != null) {
                heap.offer(list);
            }
        }
        if (heap.isEmpty()) {
            return null;
        }

        // 保存头节点
        ListNode head = heap.poll();
        ListNode pre = head;
        while (pre != null) {
            if (pre.next != null) {
                heap.offer(pre.next);
            }
            pre.next = heap.poll();
            pre = pre.next;
        }
        return head;
    }
}
